package cn.fuxi2022.module.pay.controller;

import cn.fuxi2022.commons.redis.service.CaptchaService;
import cn.fuxi2022.core.exception.SmartGroupException;
import cn.fuxi2022.core.utils.JwtUtils;
import cn.fuxi2022.core.utils.PageUtils;
import cn.fuxi2022.feign.api.GroupAuth;
import cn.fuxi2022.model.empty.applets.GroupStudentPayLog;
import cn.fuxi2022.model.resp.R;
import cn.fuxi2022.module.info.service.GroupStudentInfoService;
import cn.fuxi2022.module.pay.service.GroupStudentPayLogService;
import cn.fuxi2022.module.pay.service.WeChatPayService;
import cn.fuxi2022.rabbitmq.appletsPay.properties.WeChatMQProperties;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 社员支付日志表 前端控制器
 * </p>
 *
 * @author Fuxi
 * @since 2022-09-26 16:53:28
 */
@RestController
@RequestMapping("/admin/studentPayLog")
public class GroupStudentPayLogController {

    @Autowired
    private GroupStudentInfoService groupStudentInfoService;

    @Autowired
    private GroupStudentPayLogService groupStudentPayLogService;

    @Autowired
    private WeChatPayService weChatPayService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestBody Map<String, Object> params) {
        // 判断是否条件查询
        if (ObjectUtils.isEmpty(params.get("pay_status"))) {
            // 若当前没有传递支付状态，说明没有条件查询
            // 查询学生信息位于阶段1后的数据
            params.put("is_student", "1");
        }
        PageUtils page = groupStudentInfoService.queryPage(params);

        List<Map> studentList = page.getList().stream().map((Function<Object, Map>) o -> {
            // 1.学生信息对象转化为map
            Map map = JSONObject.parseObject(JSON.toJSONString(o), Map.class);
            // 删除多余信息
            map.remove("isDisabled");
            map.remove("isDisabled");

            // 2.根据学生ID查询当前学生订单
            LambdaQueryWrapper<GroupStudentPayLog> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(GroupStudentPayLog::getStudentId, map.get("studentId"));
            wrapper.orderByDesc(GroupStudentPayLog::getGmtCreate);

            // 3.将订单信息放入列表
            map.put("payLogList", groupStudentPayLogService.list(wrapper));

            return map;
        }).collect(Collectors.toList());

        // 4.重新设置分页数据
        page.setList(studentList);

        return R.ok().data(page);
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") String id) {
        GroupStudentPayLog groupStudentPayLog = groupStudentPayLogService.getById(id);

        return R.ok().put("groupStudentPayLog", groupStudentPayLog);
    }

    /**
     * 获取订单超时时间
     */
    @GetMapping("/properties")
    public R getPayProperties(){
        return R.ok().data("outTime", WeChatMQProperties.GROUP_ORDER_TTL_ORDER_QUEUE_TIME);
    }

    @Autowired
    private GroupAuth groupAuth;


    @GetMapping("/refundOrder/captcha")
    public R refundOrderSendCaptcha(HttpServletRequest httpServletRequest) {
        // 当前的管理员用户
        String id = JwtUtils.getMemberIdByJwtToken(httpServletRequest);
        // 获取当前用户的手机号
        String phone = groupAuth.getPhoneById(id);
        // 发送验证码
        groupStudentInfoService.getCaptcha(phone);
        return R.ok("发送验证码成功");
    }

    @Autowired
    private CaptchaService captchaService;

    /**
     * 成功的订单退款
     */
    @GetMapping("/refundOrder/{orderNo}/{code}")
    public R refundOrder(@PathVariable("orderNo") String orderNo,@PathVariable("code") String code, HttpServletRequest httpServletRequest){
        // 当前的管理员用户
        String id = JwtUtils.getMemberIdByJwtToken(httpServletRequest);
        // 获取当前用户的手机号
        String phone = groupAuth.getPhoneById(id);

        // 判断验证码是否合法
        if (!captchaService.checkCaptcha(code, phone)) {
            throw new SmartGroupException("验证码错误，请重新输入");
        }

        weChatPayService.refundOrder(orderNo);
        return R.ok("订单退款成功");
    }

    /**
     * 将支付中的订单关闭
     */
    @GetMapping("/closeOrder/{orderNo}")
    public R closeOrder(@PathVariable("orderNo") String orderNo){
        weChatPayService.closeOrder(orderNo);
        return R.ok("手动关闭订单成功");
    }
}
